package com.exampletest.service.impl;

import com.exampletest.mapper.DynamicMapper;
import com.exampletest.model.Dynamic;
import com.exampletest.service.DynamicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DynamicServiceImpl implements DynamicService {

    @Autowired
    private DynamicMapper dynamicMapper;

    @Override
    public int publishDynamic(Dynamic dynamic) {
        return dynamicMapper.insert(dynamic);
    }

    @Override
    public int editDynamic(Dynamic dynamic) {
        return dynamicMapper.update(dynamic);
    }

    @Override
    public int deleteDynamic(Long id) {
        return dynamicMapper.deleteById(id);
    }

    @Override
    public Dynamic getDynamicById(Long id) {
        return dynamicMapper.selectById(id);
    }

    @Override
    public List<Dynamic> getDynamicList(String keyword, String author, Integer status, int offset, int pageSize) {
        return dynamicMapper.searchDynamics(keyword, author, status, offset, pageSize);
    }

    @Override
    public boolean auditDynamic(Long dynamicId, Integer newStatus, Long auditorId, String auditorName, String auditReason) {
        // 实现审核逻辑
        return false;
    }

    @Override
    public int getTotalCount(String keyword, String author, Integer status) {
        return dynamicMapper.getTotalCount(keyword, author, status);
    }
    @Override
    public Map<String, Object> getAdminDynamicList(String keyword, String author, Integer status, int offset, int pageSize) {
        List<Dynamic> list = dynamicMapper.searchDynamics(keyword, author, status, offset, pageSize);
        int totalCount = dynamicMapper.getTotalCount(keyword, author, status);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("totalPages", totalPages);
        result.put("totalCount", totalCount);
        return result;
    }

    @Override
    public boolean auditDynamic(Long dynamicId, Integer newStatus, String reason) {
        // 验证参数
        if (dynamicId == null || (newStatus != 0 && newStatus != 1)) {
            return false;
        }
        // 查询动态是否存在
        Dynamic dynamic = dynamicMapper.selectById(dynamicId);
        if (dynamic == null || dynamic.getStatus() != 0) {
            return false; // 只有待审核状态（0）才能被审核
        }
        // 更新状态
        dynamic.setStatus(newStatus);
        int rows = dynamicMapper.update(dynamic);
        return rows > 0;
    }
}